<script lang="ts" setup>
import type { Rule } from 'ant-design-vue/es/form';

import { reactive, watch } from 'vue';
import { useRouter } from 'vue-router';

import { Title } from '@vben/common-ui';

import {
  Button,
  Form,
  FormItem,
  Input,
  InputPassword,
  message,
} from 'ant-design-vue';

import { resetPWD } from '#/api';
import { useAuthStore } from '#/store';

const userStore = useAuthStore();
const router = useRouter();
userStore.refreshCaptchaImage();

const userLoginData = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
});

const validateRules: Record<string, Rule[]> = {
  username: [{ required: true, trigger: 'blur' }],
  password: [{ required: true, trigger: 'blur', min: 5, max: 15 }],
  code: [{ required: true, trigger: 'blur' }],
  uuid: [{ required: true, trigger: 'blur' }],
};
watch(userStore.captcha, () => {
  userLoginData.uuid = userStore.captcha.uuid;
});
const onFinish = () => {
  resetPWD(userLoginData).then((res) => {
    if (res.data.code === 200) {
      message.success('重置成功');

      router.replace('/auth/login');
    } else {
      message.error(res.data.msg);
      userStore.refreshCaptchaImage();
    }
  });
};
</script>

<template>
  <Form :model="userLoginData" @finish="onFinish()" :rules="validateRules">
    <div>
      <Title>
        <slot name="title"> {{ $t('authentication.forgetPassword') }} 🤦🏻‍♂️ </slot>
        <template #desc>
          <slot name="subTitle">
            {{ $t('authentication.ResetPasswordSubtitle') }}
          </slot>
        </template>
      </Title>
    </div>
    <!-- 用户名 -->
    <FormItem name="username" label="用户名">
      <Input
        placeholder="请输入用户名"
        v-model:value="userLoginData.username"
      />
    </FormItem>
    <!-- 密码 -->
    <FormItem name="password" label="密码">
      <InputPassword
        placeholder="请输入新密码"
        v-model:value="userLoginData.password"
      />
    </FormItem>
    <FormItem name="uuid" class="hidden">
      <Input :value="userLoginData.uuid" />
    </FormItem>
    <!-- 验证码 -->
    <FormItem name="code" label="验证码">
      <div class="flex gap-2">
        <Input placeholder="验证码" v-model:value="userLoginData.code" />
        <img
          :src="userStore.captcha.image"
          alt="验证码"
          class="h-[32px]"
          @click="userStore.refreshCaptchaImage()"
        />
      </div>
    </FormItem>

    <!-- 提交区 -->
    <FormItem>
      <Button type="primary" block html-type="submit" class="w-full">
        重置密码
      </Button>
    </FormItem>
    <FormItem>
      <Button block @click="$router.push('/auth/login')" class="w-full">
        返回
      </Button>
    </FormItem>
  </Form>
</template>
<style scoped>
:deep(.ant-form-item-label) {
  display: none;
}
</style>
